from tortoise.models import Model
from tortoise import fields


class BaseModel(Model):
    """基础模型模板 - 自动添加创建时间和更新时间"""
    id = fields.IntField(pk=True)
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_now=True)

    class Meta:
        abstract = True  # 标记为抽象模型，不会创建表


class User(BaseModel):
    """用户表 - 核心用户信息"""
    username = fields.CharField(max_length=64, unique=True)
    password = fields.CharField(max_length=255, null=True)  # 第三方登录用户可以没有密码
    email = fields.CharField(max_length=255, null=True, unique=True)
    phone = fields.CharField(max_length=20, null=True)
    avatar = fields.CharField(max_length=500, null=True)  # 头像URL
    is_active = fields.BooleanField(default=True)  # 是否激活
    is_real = fields.IntField(default=0)  # 0未实名1已实名2待审核

    class Meta:
        table = "users"

    def __str__(self) -> str:
        return f"User<{self.id}:{self.username}>"


class OAuthAccount(BaseModel):
    """第三方登录账号表"""
    user = fields.ForeignKeyField(
        'models.User',
        related_name='oauth_accounts',
        on_delete=fields.CASCADE
    )
    # 第三方平台名称：dingtalk, wechat, github 等
    provider = fields.CharField(max_length=32)
    # 第三方平台的用户ID
    provider_user_id = fields.CharField(max_length=255)
    access_token = fields.CharField(max_length=500, null=True)  # 访问令牌（可选保存）
    refresh_token = fields.CharField(max_length=500, null=True)  # 刷新令牌（可选保存）
    expires_at = fields.DatetimeField(null=True)  # 令牌过期时间
    extra_data = fields.JSONField(null=True)  # 额外数据（如昵称、头像等）

    class Meta:
        table = "oauth_accounts"
        unique_together = (("provider", "provider_user_id"),)  # 同一平台的用户ID唯一
        indexes = [["user_id"], ["provider", "provider_user_id"]]

    def __str__(self) -> str:
        return f"OAuthAccount<{self.provider}:{self.provider_user_id}>"


class IDCardInfo(BaseModel):
    """身份证信息表"""
    user = fields.ForeignKeyField(
        'models.User',
        related_name='idcard_info',
        on_delete=fields.CASCADE,
        description="关联用户"
    )
    name = fields.CharField(max_length=50, description="姓名")
    idcard_number = fields.CharField(
        max_length=18, unique=True, description="身份证号"
    )
    gender = fields.CharField(max_length=10, null=True, description="性别")
    birth_date = fields.CharField(
        max_length=50, null=True, description="出生日期"
    )
    # 存储原始识别数据（用于调试或补充信息）
    image_url = fields.JSONField(null=True, description="身份证图片URL")

    class Meta:
        table = "idcard_info"
        indexes = [["user_id"], ["idcard_number"]]

    def __str__(self) -> str:
        return f"IDCardInfo<{self.name}:{self.idcard_number}>"


class SportType(BaseModel):
    code = fields.CharField(
        max_length=50, unique=True, description="内部代码（例：outdoor_run）"
    )
    name_cn = fields.CharField(max_length=50, description="中文名称（例：户外跑）")
    gps_enabled = fields.BooleanField(
        default=True, description="是否使用GPS（True表示记录经纬度）"
    )
    default_pace_unit = fields.CharField(
        max_length=10, default="min/km", description="默认配速单位"
    )

    class Meta:
        table = "sport_types"


class UserTrainingRecord(BaseModel):
    id = fields.IntField(pk=True, description="主键ID")
    user_id = fields.IntField(description="用户ID")
    sport_type = fields.ForeignKeyField(
        "models.SportType",
        related_name="training_records",
        on_delete=fields.CASCADE,
        description="关联的运动类型ID"
    )
    start_time = fields.DatetimeField(description="训练开始时间")
    end_time = fields.DatetimeField(description="训练结束时间")
    duration = fields.IntField(description="训练时长（秒）")
    total_distance = fields.DecimalField(
        max_digits=6, decimal_places=2, description="总距离（公里）"
    )
    average_pace = fields.DecimalField(
        max_digits=4,
        decimal_places=2,
        null=True,
        description="平均配速（分钟/公里）"
    )
    average_speed = fields.DecimalField(
        max_digits=4,
        decimal_places=2,
        null=True,
        description="平均速度（公里/小时）"
    )
    max_speed = fields.DecimalField(
        max_digits=4,
        decimal_places=2,
        null=True,
        description="最大速度（公里/小时）"
    )
    calories = fields.DecimalField(
        max_digits=6,
        decimal_places=2,
        null=True,
        description="消耗卡路里（千卡）"
    )

    class Meta:
        table = "user_training_records"


class UserNotification(BaseModel):
    """用户通知表 - 存储未送达的消息"""
    user = fields.ForeignKeyField(
        'models.User',
        related_name='notifications',
        on_delete=fields.CASCADE,
        description="关联用户"
    )
    message = fields.JSONField(description="通知消息内容")
    created_at = fields.DatetimeField(
        auto_now_add=True, description="创建时间"
    )

    class Meta:
        table = "user_notifications"
        indexes = [["user_id"]]

    def __str__(self) -> str:
        # user_id is automatically created by Tortoise ORM for the user FK
        user_id = getattr(self, 'user_id', 'unknown')
        return f"UserNotification<{self.id}:{user_id}>"


class Notification(BaseModel):
    """系统通知表 - 存储所有通知记录"""
    user = fields.ForeignKeyField(
        'models.User',
        related_name='system_notifications',
        on_delete=fields.CASCADE,
        description="关联用户"
    )
    title = fields.CharField(max_length=255, description="通知标题")
    content = fields.TextField(description="通知内容")
    type = fields.CharField(
        max_length=50,
        default='system',
        description="通知类型：system/success/warning/error"
    )
    is_read = fields.BooleanField(default=False, description="是否已读")
    status = fields.IntField(default=1, description="状态：0禁用 1启用")
    extra_data = fields.JSONField(null=True, description="额外数据")
    
    class Meta:
        table = "notifications"
        indexes = [
            ["user_id"],
            ["is_read"],
            ["created_at"],
            ["user_id", "is_read"],  # 复合索引，常用于查询未读通知
        ]
        ordering = ["-created_at"]  # 默认按创建时间倒序

    def __str__(self) -> str:
        user_id = getattr(self, 'user_id', 'unknown')
        return f"Notification<{self.id}:{user_id}:{self.title}>"
